package com.ruoyi.basicdata.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.nacos.common.codec.Base64;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.ruoyi.basicdata.domain.Resident;
import com.ruoyi.basicdata.dto.LoginDto;
import com.ruoyi.basicdata.dto.UserDto;
import com.ruoyi.basicdata.mapper.ResidentMapper;
import com.ruoyi.basicdata.service.IResidentService;
import com.ruoyi.basicdata.utils.AesUtil;
import com.ruoyi.basicdata.utils.Cons;
import com.ruoyi.basicdata.utils.QRCodeUtil;
import com.ruoyi.basicdata.vo.HslogVo;
import com.ruoyi.basicdata.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.basicdata.domain.User;
import com.ruoyi.basicdata.service.IUserService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 用户管理Controller
 *
 * @author ruoyi
 * @date 2023-04-05
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;



    /**
     * 查询用户管理列表
     */
    @RequiresPermissions("basicdata:user:list")
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户管理列表
     */
    @RequiresPermissions("basicdata:user:export")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
    @RequiresPermissions("basicdata:user:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增用户管理
     */
    @RequiresPermissions("basicdata:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户管理
     */
    @RequiresPermissions("basicdata:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user) {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户管理
     */
    @RequiresPermissions("basicdata:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }


    /**
     * 图片验证码功能
     */
    @RequiresPermissions("basicdata:user:ImageVerifyCode")
    @GetMapping("/image/{imageCodeKey}")
    public AjaxResult ImageVerifyCode(@PathVariable("imageCodeKey") String key) {
        try {
            String s = userService.imageVerifyCode(key);
            return AjaxResult.success(s);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 用户注册
     */
    @RequiresPermissions("basicdata:user:register")
    @Log(title = "注册", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Valid UserDto dto) {
        try {
            return userService.register(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }

    }

    /**
     * 用户登录
     */
    @RequiresPermissions("basicdata:user:register")
    @Log(title = "登录", businessType = BusinessType.INSERT)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid LoginDto dto) {
        try {
            return userService.login(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 二维码生成接口
     * HttpServletResponse response
     */
    @RequiresPermissions("basicdata:user:qrcode")
    @Log(title = "二维码", businessType = BusinessType.INSERT)
    @PostMapping("/qrcode")
    public AjaxResult qrcode(@RequestBody LoginVo vo) throws Exception {
        String task = vo.getTask();
        String user = vo.getUser();
        String text = " http://localhost/hslog?user=" + user + "&task=" + task;
        BufferedImage bufferedImage = QRCodeUtil.getBufferedImage(text);
        String s = bufferedImageToBase64(bufferedImage);
        return AjaxResult.success(s);
    }

    /**
     * 扫码二维码后 获取信息
     * HttpServletResponse response
     */
    @RequiresPermissions("basicdata:user:qrcode")
    @Log(title = "扫码获取信息", businessType = BusinessType.INSERT)
    @PostMapping("/returnMessage")
    public AjaxResult returnMessage(@RequestBody LoginVo vo) throws Exception {
        return AjaxResult.success(userService.returnMessage(vo));
    }


    /**
     * base64 编码
     */
    public String bufferedImageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = Base64.encodeBase64(stream.toByteArray());
        String base64 = new String(bytes);
        return base64;
    }


}
